package com.itxuhang.order.controller;

import com.itxuhang.common.pojo.Item;
import com.itxuhang.common.pojo.Order;
import com.itxuhang.order.feign.ItemService;
import com.itxuhang.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class OrderController {

    @Autowired
    private OrderService orderService ;

    @Autowired
    private ItemService itemService;

//    @Autowired
//    private RestTemplate restTemplate;

//    @Autowired
//    private DiscoveryClient discoveryClient;

    //RESTful格式请求URL
    @RequestMapping("/order/{id}/{num}/{uid}")
    public String saveOrder(@PathVariable Integer id,@PathVariable Integer num,@PathVariable Integer uid){
        // 查询商品信息，验证商品库存

//        Item item = itemService.getItemById(id);
        // 需要写死服务提供者的信息
//        ServiceInstance serviceInstance = discoveryClient.getInstances("item-service").get(0);
//        String url = "http://localhost:8081/item/1";
        /*List<ServiceInstance> instances = discoveryClient.getInstances("item-service");
        int index = new Random().nextInt(instances.size());
        ServiceInstance serviceInstance = instances.get(index);


        String host = serviceInstance.getHost();
        int port = serviceInstance.getPort();

        String url = "http://"+host+":"+port+"/item/"+id;
        System.out.println(url);*/

        /*String url = "http://item-service/item/"+id;
        Item item = restTemplate.getForObject(url,Item.class);*/

        Item item = itemService.findUserById(id);
        if (item == null){
            return "商品ID为"+id+"的商品不存在！！！";
        }

        // 保存订单信息
        Order order = new Order();
        order.setUid(uid);
        order.setUname("风骚小妲己");
        order.setItemid(item.getId());
        order.setItemname(item.getName());
        order.setItemprice(item.getPrice());
        order.setNumber(num);
        //订单其他信息，我们先不考虑了，比如配送单信息、优惠信息、子订单信息等

        orderService.save(order);

        return "OK";
    }
}
